<?php


namespace App\Services;


use App\Model\Message;
use Carbon\Carbon;
use Swoole\WebSocket\Frame;
use Swoole\WebSocket\Server;

class ChatService
{
    public static function send(Frame $frame, Server $server, array $message): void
    {
        $userId = redis()->hGet('im_user_online', (string)$frame->fd);
        $targetUserFd = redis()->hGet('user_id_to_fd', (string)$message['target_user_id']);

        $msgData = [
            'action' => 'msg_from_user',
            'message' => [
                'time' => Carbon::now(),
                'type' => 0,
                'body' => $message['message']['body'],
            ],
            'from_user' => [
                'id' => $userId
            ],
            'target_user' => [
                'id' => $message['target_user_id']
            ]
        ];

        if ($server->isEstablished((int)$targetUserFd)) {
            $msgData['message']['type'] = 1;
            $server->push($targetUserFd, json_encode($msgData, 256));
        }

        $server->push($frame->fd, json_encode($msgData, 256));

        self::save($msgData);
    }

    public static function save(array $msgData)
    {
        go(fn() => Message::query()
            ->create([
                'from_uid' => $msgData['from_user']['id'],
                'target_uid' => $msgData['target_user']['id'],
                'time' => $msgData['message']['time'],
                'type' => $msgData['message']['type'],
                'body' => json_encode($msgData['message']['body'], 256),
            ]));
    }
}